import { ref } from "vue"
import { getToken } from "@/utils/user.js"
// import webSocket from "@/utils/WebSocket.js"

const websocketUrl = 'websocket/ticket/state'

let BASEURL = ''
if (import.meta.env.MODE === 'development') {
  // BASEURL = '192.168.10.117:23334'
  BASEURL = import.meta.env.VITE_PROXY
} else {
  BASEURL = import.meta.env.VITE_BASE_URL
}
BASEURL = 'test.tch.028wlkj.com:32903'

let socket = null

export const useSocket = (eventListener) => {
  const cardIdStatus = ref({})
  const initSocket = (id) => {
    socket = new WebSocket(`ws://${BASEURL}/${websocketUrl}`, )
    socket.addEventListener('open', () => {
      socket.send(id)
    })
    socket.addEventListener('message', (event) => {
      cardIdStatus.value[id] = event.data
      eventListener && eventListener(id, event)
    })
  }
  const socketClose = () => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.close()
    }
  }
  const getStatus = (status) => {
    // 0未使用 1已使用 2已过期
    if (status === '1') {
      return '已使用'
    }
    if (status === '2') {
      return '已过期'
    }
    return '未使用'
  }
  return { initSocket, socketClose, cardIdStatus, getStatus }
}